/* eslint-disable */
import React, { useEffect, useRef, useState } from 'react';
import * as echarts from 'echarts';
import { Tabs } from 'antd';
import { HexToRGB } from '@/utils/utils';
import cl from 'classnames';
import styles from './index.less';

interface Props {
  visible: boolean;
  configureMode?: string;
  groupSetting?: any;
  profileSetting?: string[];
  targetLabel?: string;
  needLogin?: 'Y' | 'N';
  androidValue?: { miniVersion: string; maxVersion: string };
  iosValue?: { miniVersion: string; maxVersion: string };
  publishTime?: string;
  expireTime?: string;
  floorName?: string;
  quickTemplate: 'white' | 'purple';
  showTitleBar: boolean;
  title: string;
  titleIcon: Array<{ src: string; width: number; height: number; iconName: string; linkType: string; link: string; linkId: string }>;
  titleIconPosition: 'L' | 'R';
  showMore: boolean;
  moreIcon: Array<{ src: string; width: number; height: number; iconName: string; linkType: string; link: string; linkId: string }>;
  moreText: string;
  jumpLink: string;
  displayMonths: number;
  enabledBalanceTypes: string[];
  balanceTypeLabels?: any;
  subtitleText?: string;
  subtitleColor?: string;
  subtitleColorOpacity?: number;
  subtitleFontSize?: string;
  defaultActiveTab?: string;
  maxTabCount: number;
  tabBorderColor?: string;
  tabBackgroundColor?: string;
  tabTextColor?: string;
  titleColor: string;
  titleColorOpacity: number;
  titleFontSize: string;
  titleFontWeight: string;
  isTitleFontBold: 'Y' | 'N';
  isTitleFontItalic: 'Y' | 'N';
  isTitleFontUnderline: 'Y' | 'N';
  titleLineHeight: string;
  titlePosition: string;
  moreColor: string;
  moreFontSize: string;
  chartTheme: string;
  selectedTabColor: string;
  chartLineColor: string;
  chartLineColorOpacity: number;
  chartAreaColor: string;
  chartAreaColorOpacity: number;
  gridLineColor: string;
  gridLineColorOpacity: number;
  tooltipBackgroundColor: string;
  tooltipBackgroundColorOpacity: number;
  tooltipTextColor: string;
  contentFontColor: string;
  contentFontColorOpacity: number;
  labelColor: string;
  labelColorOpacity: number;
  topPadding: string;
  bottomPadding: string;
  horizontalInnerPadding: string;
  topMargin: string;
  bottomMargin: string;
  horizontalOutterMargin: string;
  chartHeight?: string;
  hasBg: 'Y' | 'N';
  bgType: 'Color' | 'Image';
  bgColor: string;
  bgColorOpacity: number;
  bgImg: { src: string; width: number; height: number };
  cornerRadius: string;
  containerWidth: string;
}

export default function UsageTrendsProd2(props: Props) {
  const {
    visible = true,
    quickTemplate = 'white',
    showTitleBar = true,
    title = 'Usage Trends at Last 6 Months',
    titleIcon = [],
    titleIconPosition = 'L',
    titlePosition = 'left',
    showMore = true,
    moreIcon = [],
    moreText = 'More',
    jumpLink = '',
    displayMonths = 6,
    enabledBalanceTypes = ['Data', 'Voice', 'SMS'],
    balanceTypeLabels = {},
    subtitleText = 'Usage Trends (MB)',
    subtitleColor = '',
    subtitleColorOpacity = 100,
    subtitleFontSize = '14',
    defaultActiveTab = 'Voice',
    maxTabCount = 4,
    tabBorderColor = '#d9d9d9',
    tabBackgroundColor = '#ffffff',
    tabTextColor = '#545454',
    titleColor = '',
    titleColorOpacity = 100,
    titleFontSize = '18',
    titleFontWeight = '700',
    isTitleFontBold = 'Y',
    isTitleFontItalic = 'N',
    isTitleFontUnderline = 'N',
    titleLineHeight = '24',
    moreColor = '',
    moreFontSize = '14',
    chartTheme = 'White',
    selectedTabColor = '',
    chartLineColor = '',
    chartAreaColor = '',
    gridLineColor = '#d9d9d9',
    gridLineColorOpacity = 100,
    tooltipBackgroundColor = '#ffffff',
    tooltipBackgroundColorOpacity = 100,
    tooltipTextColor = '#242424',
    labelColor = '',
    topPadding = '16',
    bottomPadding = '16',
    horizontalInnerPadding = '16',
    topMargin = '',
    bottomMargin = '',
    horizontalOutterMargin = '0',
    chartHeight = '250',
    hasBg = 'N',
    bgType = 'Color',
    bgColor = '',
    bgColorOpacity = 100,
    bgImg = { src: '', width: 0, height: 0 },
    cornerRadius = '8',
  } = props;

  const chartRef = useRef<HTMLDivElement>(null);
  const chartInstance = useRef<echarts.ECharts | null>(null);
  const limitedBalanceTypes = (enabledBalanceTypes || []).slice(0, maxTabCount);
  const initialActiveTab =
    (defaultActiveTab && limitedBalanceTypes.includes(defaultActiveTab) && defaultActiveTab) ||
    limitedBalanceTypes[0] ||
    '';
  const [activeTab, setActiveTab] = useState(initialActiveTab);
  const limitedBalanceTypesKey = JSON.stringify(limitedBalanceTypes);

  const getThemeDefaults = () => {
    if (chartTheme === 'Black') {
      return {
        bgColor: '#3434e1',
        titleColor: '#ffffff',
        moreColor: '#ffffff',
        subtitleColor: '#b5b5b5',
        selectedTabColor: '#07d39f',
        chartLineColor: '#07d39f',
        chartAreaColor: 'rgba(7, 211, 159, 0.2)',
        labelColor: '#b5b5b5',
      };
    }
    return {
      bgColor: '#f1f1f1',
      titleColor: '#242424',
      moreColor: '#242424',
      subtitleColor: '#545454',
      selectedTabColor: '#3434e1',
      chartLineColor: '#5d5de7',
      chartAreaColor: 'rgba(93, 93, 231, 0.2)',
      labelColor: '#545454',
    };
  };

  const themeDefaults = getThemeDefaults();
  const numericOutterMargin = Number(horizontalOutterMargin || 0);

  const bgStyle = {
    marginTop: topMargin ? topMargin + 'px' : undefined,
    marginBottom: bottomMargin ? bottomMargin + 'px' : undefined,
    marginLeft: numericOutterMargin + 'px',
    marginRight: numericOutterMargin + 'px',
    paddingTop: topPadding + 'px',
    paddingBottom: bottomPadding + 'px',
    paddingLeft: horizontalInnerPadding + 'px',
    paddingRight: horizontalInnerPadding + 'px',
    backgroundColor: hasBg === 'Y' && bgType === 'Color' ? HexToRGB(bgColor || themeDefaults.bgColor, bgColorOpacity) : 'transparent',
    backgroundImage: hasBg === 'Y' && bgType === 'Image' && bgImg?.src ? 'url(' + bgImg.src + ')' : 'none',
    backgroundPosition: 'top center',
    backgroundRepeat: 'no-repeat',
    backgroundSize: 'cover',
    borderRadius: cornerRadius ? cornerRadius + 'px' : undefined,
    border: hasBg === 'N' && quickTemplate === 'white' ? '1px dashed #e6e6e6' : 'none',
  };

  const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  const getMonthLabels = () => {
    const currentMonth = new Date().getMonth();
    const labels = [];
    for (let i = displayMonths - 1; i >= 0; i--) {
      const monthIndex = (currentMonth - i + 12) % 12;
      labels.push(months[monthIndex]);
    }
    return labels;
  };

  const generateMockData = () => Array.from({ length: displayMonths }, () => Math.floor(Math.random() * 150) + 50);

  useEffect(() => {
    if (!limitedBalanceTypes.length) {
      if (activeTab) {
        setActiveTab('');
      }
      return;
    }
    if (activeTab && limitedBalanceTypes.includes(activeTab)) {
      return;
    }
    if (defaultActiveTab && limitedBalanceTypes.includes(defaultActiveTab)) {
      setActiveTab(defaultActiveTab);
      return;
    }
    setActiveTab(limitedBalanceTypes[0]);
  }, [defaultActiveTab, activeTab, limitedBalanceTypesKey]);

  useEffect(() => {
    if (!chartRef.current) return;
    if (!chartInstance.current) chartInstance.current = echarts.init(chartRef.current);

    const finalChartLineColor = chartLineColor || themeDefaults.chartLineColor;
    const finalChartAreaColor = chartAreaColor || themeDefaults.chartAreaColor;
    const finalLabelColor = labelColor || themeDefaults.labelColor;

    chartInstance.current.setOption({
      grid: { top: 20, right: 20, bottom: 30, left: 30 },
      xAxis: {
        type: 'category',
        data: getMonthLabels(),
        axisLine: { lineStyle: { color: HexToRGB(gridLineColor, gridLineColorOpacity) } },
        axisLabel: { color: finalLabelColor, fontSize: 12 },
        axisTick: { show: true, alignWithLabel: true, lineStyle: { color: HexToRGB(gridLineColor, gridLineColorOpacity) } },
      },
      yAxis: {
        type: 'value',
        axisLine: { show: false },
        axisTick: { show: false },
        axisLabel: { color: finalLabelColor, fontSize: 12 },
        splitLine: { lineStyle: { type: 'dashed', color: HexToRGB(gridLineColor, gridLineColorOpacity) } },
      },
      tooltip: {
        trigger: 'axis',
        backgroundColor: HexToRGB(tooltipBackgroundColor, tooltipBackgroundColorOpacity),
        textStyle: { color: tooltipTextColor },
        formatter: (params: any) => {
          const data = params[0];
          const unit = activeTab === 'Data' ? 'MB' : activeTab === 'Voice' ? 'Min' : activeTab === 'SMS' ? 'SMS' : '$';
          return '<div style="padding:12px;text-align:center"><div style="font-weight:700;font-size:14px">' + data.value + '.00 ' + unit + '</div><div style="font-size:12px;color:#545454">Total</div></div>';
        },
      },
      series: [{
        type: 'line',
        data: generateMockData(),
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        lineStyle: { color: finalChartLineColor, width: 2 },
        itemStyle: { color: finalChartLineColor, borderColor: '#ffffff', borderWidth: 2 },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: finalChartAreaColor },
            { offset: 1, color: chartTheme === 'Black' ? 'rgba(7, 211, 159, 0)' : 'rgba(93, 93, 231, 0)' },
          ]),
        },
      }],
    });

    const handleResize = () => setTimeout(() => chartInstance.current?.resize(), 100);
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, [displayMonths, activeTab, chartLineColor, chartAreaColor, gridLineColor, gridLineColorOpacity, labelColor, chartTheme, tooltipBackgroundColor, tooltipBackgroundColorOpacity, tooltipTextColor]);

  const finalTitleColor = titleColor || themeDefaults.titleColor;
  const finalMoreColor = moreColor || themeDefaults.moreColor;
  const finalSubtitleColor = themeDefaults.subtitleColor;
  const finalSelectedTabColor = selectedTabColor || themeDefaults.selectedTabColor;

  const computedTitleFontWeight = isTitleFontBold === 'Y' ? '700' : (titleFontWeight || '600');
  const computedTitleLineHeight = titleLineHeight ? `${titleLineHeight}px` : '24px';

  const handleMoreClick = () => {
    if (jumpLink) {
      const linkType = moreIcon?.[0]?.linkType || '';
      const linkId = moreIcon?.[0]?.linkId || '';
      if (linkType && linkId) {
        console.log('Navigate to:', { linkType, linkId, jumpLink });
      } else {
        window.location.href = jumpLink;
      }
    }
  };

  return (
    <div className={cl(styles.wrap, { hidden: !visible })}>
      <div className={styles.container} style={bgStyle}>
        {showTitleBar && (
          <div className={styles.header}>
            <div className={styles.titleRow} style={{ justifyContent: 'space-between' }}>
              <div className={styles.titleSection} style={{ justifyContent: titlePosition === 'center' ? 'center' : titlePosition === 'right' ? 'flex-end' : 'flex-start', flex: titlePosition === 'center' ? '1' : undefined }}>
                {titleIconPosition === 'L' && titleIcon?.[0]?.src && <img src={titleIcon[0].src} alt="" className={styles.titleIcon} />}
                <div className={styles.title} style={{ color: HexToRGB(finalTitleColor, titleColorOpacity), fontSize: titleFontSize + 'px', fontWeight: computedTitleFontWeight, lineHeight: computedTitleLineHeight, fontStyle: isTitleFontItalic === 'Y' ? 'italic' : 'normal', textDecoration: isTitleFontUnderline === 'Y' ? 'underline' : 'none' }}>
                  {title}
                </div>
                {titleIconPosition === 'R' && titleIcon?.[0]?.src && <img src={titleIcon[0].src} alt="" className={styles.titleIcon} />}
              </div>
              {showMore && (
                <div className={styles.moreSection} onClick={handleMoreClick} style={{ cursor: jumpLink ? 'pointer' : 'default' }}>
                  <span className={styles.moreText} style={{ color: HexToRGB(finalMoreColor, titleColorOpacity), fontSize: moreFontSize + 'px', fontWeight: '700' }}>{moreText}</span>
                  {moreIcon?.[0]?.src && <img src={moreIcon[0].src} alt="" className={styles.moreIcon} />}
                  {!moreIcon?.[0]?.src && <span className={styles.arrow}>›</span>}
                </div>
              )}
            </div>
            <div className={styles.subtitle} style={{ color: HexToRGB(subtitleColor || finalSubtitleColor, subtitleColorOpacity), fontSize: subtitleFontSize + 'px', fontWeight: '400', textAlign: titlePosition === 'center' ? 'center' : titlePosition === 'right' ? 'right' : 'left' }}>
              {subtitleText}
            </div>
          </div>
        )}
        <Tabs
          activeKey={activeTab}
          onChange={(key) => setActiveTab(key)}
          className={styles.tabs}
          items={limitedBalanceTypes.map((type) => ({
            key: type,
            label: balanceTypeLabels?.[type] || type,
          }))}
          style={{
            '--selected-tab-color': finalSelectedTabColor,
            '--tab-border-color': tabBorderColor,
            '--tab-background-color': tabBackgroundColor,
            '--tab-text-color': tabTextColor,
          } as React.CSSProperties}
        />
        <div ref={chartRef} className={styles.chart} style={{ '--chart-height': chartHeight + 'px' } as React.CSSProperties}></div>
      </div>
    </div>
  );
}
